#include "MyStack.h"

MyStack* myStackCreate()
{
	MyStack* st = (MyStack*)malloc(sizeof(MyStack));
	if (NULL == st)
	{
		perror("malloc failed");
		exit(-1);
	}
	st->qa = QueueCreate();
	st->qb = QueueCreate();
	return st;
}

void myStackPush(MyStack* st, QDataType x)
{
	assert(st);
	if (QueueEmpty(st->qb))
		QueuePush(st->qa, x);
	else
		QueuePush(st->qa, x);
}

QDataType myStackPop(MyStack* st)
{
	assert(st);
	assert(!myStackEmpty(st));
	Queue* empty = st->qa;
	Queue* noempty = st->qb;
	if (!QueueEmpty(st->qa))
	{
		empty = st->qb;
		noempty = st->qa;
	}
	QDataType ret = noempty->tail->data;
	while (QueueSize(noempty) > 1)
	{
		QDataType ret = QueuePop(noempty);
		QueuePush(empty, ret);
	}
	QueuePop(noempty);
	return ret;
}

QDataType myStackTop(MyStack* st)
{
	assert(st);
	assert(!myStackEmpty(st));
	if (QueueEmpty(st->qb))
		return st->qa->tail->data;
	else
		return st->qb->tail->data;
}

bool myStackEmpty(MyStack* st)
{
	return (QueueEmpty(st->qa) && QueueEmpty(st->qb));
}

void myStackFree(MyStack* st)
{
	QueueDestroy(st->qa);
	QueueDestroy(st->qb);
	free(st);
}